package com.csc.mtlbatch.util;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.core.io.Resource;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.support.MessageBuilder;

public class ClsSFTPUtil implements Tasklet {

	//private String fileName;
	private Resource fileName;
    private MessageChannel sftpChannel;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ClsSFTPUtil.class);
    
	@Override
	public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
			throws Exception {
		
		Boolean result = false;
		File file = new File(fileName.getFile().getAbsolutePath().toString());
		 
        if (file.exists()) {
            Message<File> message = MessageBuilder.withPayload(file).build();
            try {
                sftpChannel.send(message);
                result = true;
            } catch (Exception e) {
            	LOGGER.error("Could not send file per SFTP: " + e);
            }
        } else {
        	LOGGER.error("File does not exist.");
        }
	 
        if (result){
        	LOGGER.info("SFTP File Success.");
        }else{
        	LOGGER.error("SFTP File Fail");
        }
        
	    return RepeatStatus.FINISHED;
	}

	public Resource getFileName() {
		return fileName;
	}

	public void setFileName(Resource fileName) {
		this.fileName = fileName;
	}

	public MessageChannel getSftpChannel() {
		return sftpChannel;
	}

	public void setSftpChannel(MessageChannel sftpChannel) {
		this.sftpChannel = sftpChannel;
	}

}
